#include <winsock2.h>
#include <ws2tcpip.h>

#include "code_trans.h"
#include "print.h"
#include "thread_pool.h"
#include "nlohmann/json_fwd.hpp"
#include "nlohmann/json.hpp"
#include "udp_receiver.h"

import utils;
import config;


int main(int argc, char** argv)
{
	init_config(argc, argv);

    std::string message;
    if (argc == 1)
    {
        printf("usage: %s message\n", argv[0]);
        message = "hello";
    }
    else
    {
        message = GetCommandLineA();
        auto subs = std::string_view(message.begin() + message.find_first_of(' ') + 1, message.end());
        while (!subs.empty() && iswblank(subs[0]))
        {
            subs = subs.substr(1);
        }
    	message = subs;
    }
    udp_sender::socket_create_parameters parameters;
    bool is_send_to_group = true;
    if(const size_t index = message.find_first_of(' '); index != std::string::npos && index >= 7 && index <= 15)
    {
	    const std::string s = message.substr(0, index);
        if(inet_addr(s.c_str()) != INADDR_NONE)
        {
            is_send_to_group = false;
            parameters.send_ip = s;
            message = message.substr(index + 1);
        }
    }
    if(is_send_to_group)
    {
        parameters.send_ip = get_config().udp_receiver_parameters.group_addr;
    }
    parameters.send_port = get_config().udp_receiver_parameters.listen_port;
    //parameters.group_addr = get_config().udp_receiver_parameters.group_addr;
    parameters.group = false;
	const udp_sender sender(parameters);

    sockaddr_in self_addr;
    int self_addr_len = sizeof(sockaddr_in);
    getsockname(sender.udp_socket, reinterpret_cast<sockaddr*>(&self_addr), &self_addr_len);
    std::string ssa = inet_ntoa(self_addr.sin_addr);

    timer timer0;
    auto result_code = sender.send({ message.begin(), message.end() });
    
    std::cout << std::format("{} Sent: \"{}\", {} bytes \n", ssa, message, result_code);
}